﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Net.Mime;
using System.Web;
using System.Web.Mvc;
using Lvzhi.AdminCenter.Extension.MvcHelper;
using Lvzhi.Core;
using Lvzhi.Entities;
using Lvzhi.Entities.BaseEnum;
using Webdiyer.WebControls.Mvc;

namespace Lvzhi.AdminCenter.Controllers
{
    public class ProductController : BaseController
    {
        private ProductCore pcore = new ProductCore();
        private UserProductCore upcore = new UserProductCore();
        private UserCore ucore = new UserCore();
        private CompanyCore ccore = new CompanyCore();
        /// <summary>
        /// 投保产品管理
        /// </summary>
        /// <returns></returns>
        public ActionResult Index(int id = 1, int size = 10, string key = "", int uid = -1)
        {
            var user = GetUser();
            ViewBag.RoleId = user.U_Role;

            Expression<Func<Core_Product, Boolean>> expr = t => t.P_State == 0;
            if (!string.IsNullOrWhiteSpace(key))
            {
                expr = expr.And(t => t.P_Name.Contains(key.Trim()));
            }
            if (uid > 0 && user.U_Id != uid)  //查看单个人的分配,且不是当前的管理员本人
            {
                using (lvzhiEntities db = new lvzhiEntities())
                {
                    IQueryable<Core_Product> rs = null;
                    rs = from a in db.Core_Product
                         join b in db.Core_UserProduct
                             on a.P_Id equals b.UP_PId
                         where b.UP_UId == user.U_Id && b.UP_UId == uid
                         orderby a.P_Createtime descending
                         select a;

                    return View(rs.Where(expr).ToList().ToPagedList(id, size));
                }

            }
            if (user.U_Role != 0) //除了超管，其他人，只能看分配的产品
            {
                using (lvzhiEntities db = new lvzhiEntities())
                {
                    IQueryable<Core_Product> rs = null;
                    rs = from a in db.Core_Product
                         join b in db.Core_UserProduct
                         on a.P_Id equals b.UP_PId
                         where b.UP_UId == user.U_Id
                         orderby a.P_Createtime descending
                         select a;

                    return View(rs.Where(expr).ToList().ToPagedList(id, size));
                }
            }
            var list = pcore.LoadEntities(expr).OrderByDescending(o => o.P_Createtime).ToPagedList(id, size);
            return View(list);
        }
        /// <summary>
        /// 产品权限
        /// </summary>
        /// <returns></returns>
        public ActionResult Allot(int id)
        {
            Core_User u = ucore.LoadEntity(o => o.U_Id == id);

            if (u == null)
            {
                throw new Exception("用户不存在");
            }

            var userproduct = upcore.LoadEntities(o => o.UP_UId == id);  //查询分配用户的所有产品


            var user = GetUser();
            ViewBag.RoleId = user.U_Role;
            ViewBag.UserId = id;
            ViewBag.UserName = Enum.GetName(typeof(ManagerRoleEnum), u.U_Role) + "：" + u.U_Name;  //待分配的用户信息



            Expression<Func<Core_Product, Boolean>> expr = t => t.P_State == 0;

            if (user.U_Role != 0) //除了超管，其他人，只能看分配的产品
            {
                using (lvzhiEntities db = new lvzhiEntities())
                {
                    var rs = from a in db.Core_Product
                             join b in db.Core_UserProduct
                                 on a.P_Id equals b.UP_PId
                             where b.UP_UId == user.U_Id && a.P_State == 0
                             orderby a.P_Createtime descending
                             select a;

                    var trs = rs.ToList().Select(a => new Core_Product()
                    {
                        P_Id = a.P_Id,
                        P_Name = a.P_Name,
                        P_Code = a.P_Code,
                        P_Timeout = a.P_Timeout,
                        P_CompanyName = a.P_CompanyName,
                        P_Createtime = a.P_Createtime,
                        P_Flag = 0 //userproduct.Any(o => o.UP_PId == a.P_Id) ? 1 : 0  //是否有分配 1：有  0无
                    }).ToList();

                    //trs = rs.AsNoTracking().ToList();// rs.Where(expr).ToList();
                    return View(trs);
                }
            }
            var list = pcore.LoadEntities(expr).OrderByDescending(o => o.P_Createtime).ToList().Select(a => new Core_Product()
            {

                P_Id = a.P_Id,
                P_Name = a.P_Name,
                P_Code = a.P_Code,
                P_Timeout = a.P_Timeout,
                P_CompanyName = a.P_CompanyName,
                P_Createtime = a.P_Createtime,
                P_Flag = userproduct.Any(o => o.UP_PId == a.P_Id) ? 1 : 0  //是否有分配 1：有  0无
            });
            return View(list.ToList());
        }
        [HttpPost]
        public string Allot(int uid, string ids)
        {
            var user = ucore.LoadEntity(o => o.U_Id == uid);
            if (user != null)
            {
                //要分配的产品
                var products = pcore.LoadEntities().ToList().Where(o => ids.IndexOf(o.P_Id + ",") > -1).Select(o => new Core_UserProduct()
                {
                    UP_UId = uid,
                    UP_PId = o.P_Id,
                    UP_UName = user.U_Name,
                    UP_PName = o.P_Name,
                    UP_Time = DateTime.Now
                }).ToList();

                if (products.Any())
                {
                    //先删除之前数据库存在的
                    upcore.DeleteByExtended(o => o.UP_UId == uid);
                    if (upcore.AddEntities(products))
                    {
                        return "分配成功";
                    }
                }

            }

            return "分配失败";
        }

        /// <summary>
        /// 编辑产品
        /// </summary>
        /// <returns></returns>
        public ActionResult Edit(Guid? id)
        {
            Core_Product pinfo = null;
            if (id.HasValue)
            {
                pinfo = pcore.LoadEntity(o => o.P_Id == id);
            }
            else
            {
                pinfo = new Core_Product()
                {
                    P_Id = Guid.Empty
                };
            }

            TempData["CompanyList"] = ccore.LoadEntities(o => o.C_State == 0).Select(o => new SelectListItem()
            {
                Value = o.C_Id.ToString(),
                Text = o.C_Name,
                Selected = o.C_Id == pinfo.P_CompanyId
            });


            return View(pinfo);
        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Edit(Core_Product obj)
        {
            bool rs = false;
            obj.P_Createtime = DateTime.Now;

            var printflag = Request.Form["printFlag"].Split(',');
            obj.P_PrintTicket = printflag.Any(o => o == "1") ? 1 : 0;
            obj.P_PrintAfter = printflag.Any(o => o == "0") ? 1 : 0;

            if (obj.P_Id != Guid.Empty)
            {
                rs = pcore.UpdateEntity(obj);
            }
            else
            {
                pcore.AddEntity(obj);
                rs = true;
            }
            if (rs)
            {
                return RedirectToAction("Index");
            }
            return View(obj);
        }
    }
}